<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>管理员仪表板 - 家电维修系统</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/all.min.css}" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background-color: #343a40;
            padding-top: 20px;
        }
        .sidebar .nav-link {
            color: #fff;
            padding: 10px 20px;
        }
        .sidebar .nav-link:hover {
            background-color: #495057;
        }
        .sidebar .nav-link.active {
            background-color: #0d6efd;
        }
        .main-content {
            padding: 20px;
        }
        .stat-card {
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .chart-container {
            height: 300px;
            margin-bottom: 20px;
        }
        /* 添加富文本编辑器样式 */
        #editor {
            height: 200px;
            max-height: 200px;
            overflow-y: auto;
        }
        .ql-editor {
            min-height: 150px;
            max-height: 150px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-3 col-lg-2 px-0 sidebar">
                <h4 class="text-white text-center mb-4">家电维修管理后台</h4>
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link active" href="#" data-page="dashboard">
                            <i class="fas fa-tachometer-alt me-2"></i>仪表板
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="announcement">
                            <i class="fas fa-bullhorn me-2"></i>公告管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="users">
                            <i class="fas fa-users me-2"></i>用户管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="repairmen">
                            <i class="fas fa-tools me-2"></i>维修工管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="orders">
                            <i class="fas fa-clipboard-list me-2"></i>订单管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="tracking">
                            <i class="fas fa-map-marker-alt me-2"></i>轨迹管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="forum">
                            <i class="fas fa-comments me-2"></i>论坛管理
                        </a>
                    </li>
                    <li class="nav-item mt-4">
                        <a class="nav-link" href="#" id="logout">
                            <i class="fas fa-sign-out-alt me-2"></i>退出登录
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 主要内容区 -->
            <div class="col-md-9 col-lg-10 main-content">
                <!-- 仪表板页面 -->
                <div id="dashboard-page">
                    <h2 class="mb-4">仪表板</h2>
                    <div class="row">
                        <div class="col-md-3">
                            <div class="card stat-card bg-primary text-white">
                                <div class="card-body">
                                    <h5 class="card-title">总用户数</h5>
                                    <h2 class="card-text" id="total-users">0</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card stat-card bg-success text-white">
                                <div class="card-body">
                                    <h5 class="card-title">总维修工数</h5>
                                    <h2 class="card-text" id="total-repairmen">0</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card stat-card bg-warning text-white">
                                <div class="card-body">
                                    <h5 class="card-title">待处理订单</h5>
                                    <h2 class="card-text" id="pending-orders">0</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card stat-card bg-info text-white">
                                <div class="card-body">
                                    <h5 class="card-title">今日订单</h5>
                                    <h2 class="card-text" id="today-orders">0</h2>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-4">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">订单统计</h5>
                                    <div class="chart-container" id="order-trend-chart"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">维修工统计</h5>
                                    <div class="chart-container" id="repairman-chart"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 公告管理页面 -->
                <div id="announcement-page" class="d-none">
                    <h2 class="mb-4">公告管理</h2>
                    <div class="card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h5 class="card-title mb-0">公告列表</h5>
                                <button class="btn btn-primary" onclick="showAnnouncementModal()">
                                    <i class="fas fa-plus me-2"></i>发布公告
                                </button>
                            </div>
                            <div class="table-responsive">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>标题</th>
                                            <th>类型</th>
                                            <th>状态</th>
                                            <th>置顶</th>
                                            <th>浏览次数</th>
                                            <th>发布时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="announcement-list">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 用户管理页面 -->
                <div id="users-page" class="d-none">
                    <h2 class="mb-4">用户管理</h2>
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>用户名</th>
                                            <th>真实姓名</th>
                                            <th>电话</th>
                                            <th>邮箱</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="users-table">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 维修工管理页面 -->
                <div id="repairmen-page" class="d-none">
                    <h2 class="mb-4">维修工管理</h2>
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>用户名</th>
                                            <th>真实姓名</th>
                                            <th>电话</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="repairmen-table">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 订单管理页面 -->
                <div id="orders-page" class="d-none">
                    <h2 class="mb-4">订单管理</h2>
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>订单号</th>
                                            <th>用户</th>
                                            <th>维修工</th>
                                            <th>状态</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="orders-table">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 论坛管理页面 -->
                <div id="forum-page" class="d-none">
                    <h2 class="mb-4">论坛管理</h2>
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>标题</th>
                                            <th>发帖人</th>
                                            <th>发帖人类型</th>
                                            <th>发布时间</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="forum-posts-table">
                                    </tbody>
                                </table>
                            </div>
                            <!-- 分页控件 -->
                            <nav aria-label="Page navigation" class="mt-4">
                                <ul class="pagination justify-content-center" id="forum-pagination">
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>

                <!-- 轨迹管理页面 -->
                <div id="tracking-page" class="d-none">
                    <h2 class="mb-4">维修工轨迹管理</h2>
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="repairmanSelect" class="form-label">选择维修工</label>
                                        <select class="form-select" id="repairmanSelect">
                                            <option value="">请选择维修工</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="trackDate" class="form-label">选择日期</label>
                                        <input type="date" class="form-control" id="trackDate">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label class="form-label">&nbsp;</label>
                                        <button class="btn btn-primary d-block" onclick="loadTrackData()">查看轨迹</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-9">
                            <div class="card">
                                <div class="card-body">
                                    <div id="trackMap" style="height: 500px;"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card mb-3">
                                <div class="card-body">
                                    <h5 class="card-title">今日统计</h5>
                                    <div class="mb-2">
                                        <small class="text-muted">总里程</small>
                                        <h4 id="totalDistance">0 km</h4>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">活动时长</small>
                                        <h4 id="totalDuration">0 小时</h4>
                                    </div>
                                    <div>
                                        <small class="text-muted">完成订单</small>
                                        <h4 id="completedOrders">0 单</h4>
                                    </div>
                                </div>
                            </div>
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">活动记录</h5>
                                    <div class="timeline" id="trackTimeline" style="max-height: 300px; overflow-y: auto;">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 公告编辑模态框 -->
    <div class="modal fade" id="announcementModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">发布公告</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="announcementForm">
                        <div class="mb-3">
                            <label for="title" class="form-label">标题</label>
                            <input type="text" class="form-control" id="title" required>
                        </div>
                        <div class="mb-3">
                            <label for="type" class="form-label">可见范围</label>
                            <select class="form-select" id="type" required>
                                <option value="0">全部可见</option>
                                <option value="1">仅用户可见</option>
                                <option value="2">仅维修工可见</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="content" class="form-label">内容</label>
                            <div id="editor"></div>
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="top">
                            <label class="form-check-label" for="top">
                                置顶公告
                            </label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveAnnouncement()">发布</button>
                    <button type="button" class="btn btn-outline-primary" onclick="saveAsDraft()">保存草稿</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加帖子详情模态框 -->
    <div class="modal fade" id="postModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="postTitle"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <small class="text-muted">
                            作者：<span id="postAuthor"></span> | 
                            发布时间：<span id="postTime"></span>
                        </small>
                    </div>
                    <div id="postContent"></div>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/js/jquery.min.js}"></script>
    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
    <script th:src="@{/js/echarts.min.js}"></script>
    <script th:src="@{/js/quill.min.js}"></script>
    <link th:href="@{/css/quill.snow.min.css}" rel="stylesheet">
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=spEZ8x14LoDN10ejoQD7GdxOEJYOwqcw"></script>
    <script>
        let quill;
        let announcementModal;
        let currentAnnouncementId = null;
        let bmap;

        // 加载公告列表
        window.loadAnnouncements = function() {
            $.ajax({
                url: '/api/admin/announcements',
                type: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
                },
                success: function(response) {
                    const tbody = $('#announcement-list');
                    tbody.empty();
                    response.forEach(announcement => {
                        const createdAt = announcement.createdAt;
                        const viewCount = announcement.viewCount;
                        tbody.append(`
                            <tr>
                                <td>${announcement.title}</td>
                                <td>${announcement.type === 0 ? '全部可见' : announcement.type === 1 ? '仅用户可见' : '仅维修工可见'}</td>
                                <!--status = 0 草稿 status = 1 已发布 2 已下线 -->
                                 <td>${announcement.status === 0 ? '草稿' : '已发布'}</td>
                                <td>${announcement.top ? '是' : '否'}</td>
                                <td>${viewCount}</td>
                                <td>${createdAt ? new Date(createdAt).toLocaleString() : '未发布'}</td>
                                <td>
                                    <button class="btn btn-sm btn-info" onclick="window.viewAnnouncement(${announcement.id})">查看</button>
                                    <button class="btn btn-sm btn-warning" onclick="window.editAnnouncement(${announcement.id})">编辑</button>
                                    <button class="btn btn-sm btn-danger" onclick="window.deleteAnnouncement(${announcement.id})">删除</button>
                                </td>
                            </tr>
                        `);
                    });
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/admin-login';
                    } else {
                        alert('加载公告列表失败');
                    }
                }
            });
        };

        // 查看公告详情
        window.viewAnnouncement = function(announcementId) {
            $.ajax({
                url: `/api/admin/announcements/${announcementId}`,
                type: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
                },
                success: function(announcement) {
                    const createdAt = announcement.createdAt;
                    alert(`
                        公告详情：
                        标题：${announcement.title}
                        类型：${announcement.type === 0 ? '全部可见' : announcement.type === 1 ? '仅用户可见' : '仅维修工可见'}
                        状态：${announcement.status === 0 ? '草稿' : '已发布'}
                        置顶：${announcement.top ? '是' : '否'}
                        浏览次数：${announcement.viewCount}
                        发布时间：${createdAt ? new Date(createdAt).toLocaleString() : '未发布'}
                        内容：${announcement.content}
                    `);
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/admin-login';
                    } else {
                        alert('加载公告详情失败');
                    }
                }
            });
        };

        // 显示公告编辑模态框
        window.showAnnouncementModal = function() {
            currentAnnouncementId = null;
            $('#announcementForm')[0].reset();
            quill.root.innerHTML = '';
            $('.modal-title').text('发布公告');
            announcementModal.show();
        };

        // 编辑公告
        window.editAnnouncement = function(announcementId) {
            $.ajax({
                url: `/api/admin/announcements/${announcementId}`,
                type: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
                },
                success: function(announcement) {
                    currentAnnouncementId = announcementId;
                    // 填充表单
                    $('#title').val(announcement.title);
                    $('#type').val(announcement.type);
                    quill.root.innerHTML = announcement.content;
                    $('#top').prop('checked', announcement.top);

                    // 更新模态框标题
                    $('.modal-title').text('编辑公告');
                    // 显示模态框
                    announcementModal.show();
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/admin-login';
                    } else {
                        alert('加载公告详情失败');
                    }
                }
            });
        };

        // 保存公告
        window.saveAnnouncement = function() {
            const formData = {
                title: $('#title').val(),
                type: parseInt($('#type').val()),
                content: quill.root.innerHTML,
                top: $('#top').prop('checked'),
                status: 1
            };

            if (currentAnnouncementId) {
                formData.id = currentAnnouncementId;
            }

            $.ajax({
                url: '/api/admin/announcements',
                type: currentAnnouncementId ? 'PUT' : 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
                },
                success: function() {
                    announcementModal.hide();
                    window.loadAnnouncements();
                    alert(currentAnnouncementId ? '公告更新成功' : '公告发布成功');
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/admin-login';
                    } else {
                        alert(currentAnnouncementId ? '更新公告失败' : '发布公告失败');
                    }
                }
            });
        };

        // 保存草稿
        window.saveAsDraft = function() {
            const formData = {
                title: $('#title').val(),
                type: parseInt($('#type').val()),
                content: quill.root.innerHTML,
                top: $('#top').prop('checked'),
                status: 0
            };

            if (currentAnnouncementId) {
                formData.id = currentAnnouncementId;
            }

            $.ajax({
                url: '/api/admin/announcements',
                type: currentAnnouncementId ? 'PUT' : 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
                },
                success: function() {
                    announcementModal.hide();
                    window.loadAnnouncements();
                    alert('草稿保存成功');
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/admin-login';
                    } else {
                        alert('保存草稿失败');
                    }
                }
            });
        };

        // 删除公告
        window.deleteAnnouncement = function(announcementId) {
            if (confirm('确定要删除这个公告吗？')) {
                $.ajax({
                    url: `/api/admin/announcements/${announcementId}`,
                    type: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
                    },
                    success: function() {
                        window.loadAnnouncements();
                        alert('公告删除成功');
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            window.location.href = '/admin-login';
                        } else {
                            alert('删除公告失败');
                        }
                    }
                });
            }
        };

        $(document).ready(function() {
            // 初始化富文本编辑器
            quill = new Quill('#editor', {
                theme: 'snow',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline', 'strike'],
                        ['blockquote', 'code-block'],
                        [{ 'header': 1 }, { 'header': 2 }],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'script': 'sub'}, { 'script': 'super' }],
                        [{ 'indent': '-1'}, { 'indent': '+1' }],
                        [{ 'direction': 'rtl' }],
                        [{ 'size': ['small', false, 'large', 'huge'] }],
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'font': [] }],
                        [{ 'align': [] }],
                        ['clean'],
                        ['link', 'image']
                    ]
                }
            });

            // 初始化模态框
            announcementModal = new bootstrap.Modal(document.getElementById('announcementModal'));

            // 检查是否已登录
            const token = localStorage.getItem('adminToken');
            if (!token) {
                window.location.href = '/admin-login';
                return;
            }

            // 加载仪表板数据
            loadDashboardData();

            // 页面切换
            $('.nav-link').click(function(e) {
                e.preventDefault();
                if ($(this).attr('id') === 'logout') {
                    logout();
                    return;
                }
                const page = $(this).data('page');
                $('.nav-link').removeClass('active');
                $(this).addClass('active');
                $('.main-content > div').addClass('d-none');
                $(`#${page}-page`).removeClass('d-none');

                // 如果切换到轨迹页面，等待DOM更新后再初始化地图
                if (page === 'tracking') {
                    setTimeout(() => {
                        initTrackingPage();
                    }, 100);
                } else if (page === 'dashboard') {
                    loadDashboardData();
                } else if (page === 'users') {
                    loadUsers();
                } else if (page === 'repairmen') {
                    loadRepairmen();
                } else if (page === 'orders') {
                    loadOrders();
                } else if (page === 'statistics') {
                    loadStatistics();
                } else if (page === 'announcement') {
                    loadAnnouncements();
                } else if (page === 'forum') {
                    loadForumPosts();
                }
            });

            // 退出登录
            function logout() {
                localStorage.removeItem('adminToken');
                window.location.href = '/login';
            }

            // 加载仪表板数据
            function loadDashboardData() {
                $.ajax({
                    url: '/api/admin/statistics',
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function(response) {
                        // 初始化订单趋势图表
                        const orderTrendChart = echarts.init(document.getElementById('order-trend-chart'));
                        orderTrendChart.setOption({
                            title: {
                                text: '订单趋势'
                            },
                            tooltip: {
                                trigger: 'axis'
                            },
                            xAxis: {
                                type: 'category',
                                data: response.orderTrend.map(item => item.date)
                            },
                            yAxis: {
                                type: 'value'
                            },
                            series: [{
                                data: response.orderTrend.map(item => item.count),
                                type: 'line',
                                smooth: true
                            }]
                        });
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });



                $.ajax({
                    url: '/api/admin/dashboard',
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function(response) {
                        $('#total-users').text(response.totalUsers);
                        $('#total-repairmen').text(response.totalRepairmen);
                        $('#pending-orders').text(response.pendingOrders);
                        $('#today-orders').text(response.todayOrders);

                        // 初始化维修工统计图表
                        const repairmanChart = echarts.init(document.getElementById('repairman-chart'));
                        repairmanChart.setOption({
                            title: {
                                text: '维修工订单完成率'
                            },
                            tooltip: {
                                trigger: 'axis'
                            },
                            xAxis: {
                                type: 'category',
                                data: response.repairmanStats.map(item => item.name)
                            },
                            yAxis: {
                                type: 'value',
                                axisLabel: {
                                    formatter: '{value}%'
                                }
                            },
                            series: [{
                                data: response.repairmanStats.map(item => item.completionRate),
                                type: 'bar'
                            }]
                        });
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            }

            // 加载用户列表
            function loadUsers() {
                $.ajax({
                    url: '/api/admin/users',
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function(response) {
                        const tbody = $('#users-table');
                        tbody.empty();
                        response.forEach(user => {
                            tbody.append(`
                                <tr>
                                    <td>${user.id}</td>
                                    <td>${user.username}</td>
                                    <td>${user.realName}</td>
                                    <td>${user.phone}</td>
                                    <td>${user.email}</td>
                                    <td>${user.status === 1 ? '正常' : '禁用'}</td>
                                    <td>
                                        <button class="btn btn-sm btn-warning" onclick="toggleUserStatus(${user.id})">
                                            ${user.status === 1 ? '禁用' : '启用'}
                                        </button>
                                    </td>
                                </tr>
                            `);
                        });
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            }

            // 加载维修工列表
            function loadRepairmen() {
                $.ajax({
                    url: '/api/admin/repairmen',
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function(response) {
                        const tbody = $('#repairmen-table');
                        tbody.empty();
                        response.forEach(repairman => {
                            tbody.append(`
                                <tr>
                                    <td>${repairman.id}</td>
                                    <td>${repairman.username}</td>
                                    <td>${repairman.realName}</td>
                                    <td>${repairman.phone}</td>
                                    <td>${repairman.status === 1 ? '正常' : '禁用'}</td>
                                    <td>
                                        <button class="btn btn-sm btn-warning" onclick="toggleRepairmanStatus(${repairman.id})">
                                            ${repairman.status === 1 ? '禁用' : '启用'}
                                        </button>
                                    </td>
                                </tr>
                            `);
                        });
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            }

            // 加载订单列表
            function loadOrders() {
                $.ajax({
                    url: '/api/admin/orders',
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function(response) {
                        const tbody = $('#orders-table');
                        tbody.empty();
                        response.forEach(order => {
                            tbody.append(`
                                <tr>
                                    <td>${order.id}</td>
                                    <td>${order.userName}</td>
                                    <td>${order.repairmanName || '未接单'}</td>
                                    <td>${getOrderStatus(order.status)}</td>
                                    <td>${new Date(order.create_time).toLocaleString()}</td>
                                    <td>
                                        <button class="btn btn-sm btn-info" onclick="viewOrderDetails(${order.id})">
                                            查看详情
                                        </button>
                                    </td>
                                </tr>
                            `);
                        });
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            }

            // 加载统计数据
            function loadStatistics() {
                $.ajax({
                    url: '/api/admin/statistics',
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function(response) {
                        // 初始化订单趋势图表
                        const orderTrendChart = echarts.init(document.getElementById('order-trend-chart'));
                        orderTrendChart.setOption({
                            title: {
                                text: '订单趋势'
                            },
                            tooltip: {
                                trigger: 'axis'
                            },
                            xAxis: {
                                type: 'category',
                                data: response.orderTrend.map(item => item.date)
                            },
                            yAxis: {
                                type: 'value'
                            },
                            series: [{
                                data: response.orderTrend.map(item => item.count),
                                type: 'line',
                                smooth: true
                            }]
                        });

                        // 初始化维修工绩效图表
                        const repairmanPerformanceChart = echarts.init(document.getElementById('repairman-performance-chart'));
                        repairmanPerformanceChart.setOption({
                            title: {
                                text: '维修工绩效'
                            },
                            tooltip: {
                                trigger: 'axis'
                            },
                            xAxis: {
                                type: 'category',
                                data: response.repairmanPerformance.map(item => item.name)
                            },
                            yAxis: {
                                type: 'value'
                            },
                            series: [{
                                data: response.repairmanPerformance.map(item => item.completedOrders),
                                type: 'bar',
                                name: '完成订单数'
                            }]
                        });
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            }

            // 获取订单状态文本
            function getOrderStatus(status) {
                const statusMap = {
                    0: '待接单',
                    1: '已接单',
                    2: '维修中',
                    3: '已完成',
                    4: '已取消'
                };
                return statusMap[status] || '未知状态';
            }

            // 切换用户状态
            window.toggleUserStatus = function(userId) {
                $.ajax({
                    url: `/api/admin/users/${userId}/status`,
                    type: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function() {
                        loadUsers();
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            };

            // 切换维修工状态
            window.toggleRepairmanStatus = function(repairmanId) {
                $.ajax({
                    url: `/api/admin/repairmen/${repairmanId}/status`,
                    type: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function() {
                        loadRepairmen();
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            };

            // 查看订单详情
            window.viewOrderDetails = function(orderId) {
                $.ajax({
                    url: `/api/admin/orders/${orderId}`,
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function(order) {
                        alert(`
                            订单详情：
                            订单号：${order.id}
                            用户：${order.userName}
                            维修工：${order.repairmanName || '未接单'}
                            状态：${getOrderStatus(order.status)}
                            创建时间：${new Date(order.create_time).toLocaleString()}
                            地址：${order.address}
                            描述：${order.description}
                        `);
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            };

            // 初始化轨迹管理页面
            function initTrackingPage() {
                // 加载维修工列表
                $.ajax({
                    url: '/api/admin/repairmen',
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function(response) {
                        const select = $('#repairmanSelect');
                        select.empty();
                        select.append('<option value="">请选择维修工</option>');
                        response.forEach(repairman => {
                            if (repairman.status === 1) {
                                select.append(`<option value="${repairman.id}">${repairman.realName}</option>`);
                            }
                        });
                    }
                });

                // 设置默认日期为今天
                const today = new Date().toISOString().split('T')[0];
                $('#trackDate').val(today);

                // 初始化百度地图
                initBaiduMap();
            }

            // 初始化百度地图
            function initBaiduMap() {
                // 确保地图容器已经存在并且可见
                const mapContainer = document.getElementById("trackMap");
                if (!mapContainer) {
                    console.error("Map container not found");
                    return;
                }

                // 确保地图容器在可见状态下初始化
                if (mapContainer.offsetWidth === 0 || mapContainer.offsetHeight === 0) {
                    $('#tracking-page').removeClass('d-none');
                }

                if (!bmap) {
                    try {
                        bmap = new BMapGL.Map("trackMap");
                        bmap.enableScrollWheelZoom();
                        
                        // 添加3D控件
                        bmap.addControl(new BMapGL.NavigationControl3D());
                        bmap.addControl(new BMapGL.ScaleControl());
                        bmap.addControl(new BMapGL.ZoomControl());
                        
                        // 设置地图3D视角
                        bmap.setTilt(60);
                        bmap.setHeading(0);
                        
                        // 设置地图样式为暗色主题
                        bmap.setMapStyleV2({
                            styleId: '4035ec0d3568b34d769a4302c5393cb8'
                        });
                        
                        // 默认中心点设置为北京
                        const point = new BMapGL.Point(116.404, 39.915);
                        bmap.centerAndZoom(point, 12);
                    } catch (error) {
                        console.error("Failed to initialize map:", error);
                    }
                }
            }

            // 加载轨迹数据
            window.loadTrackData = function() {
                const repairmanId = $('#repairmanSelect').val();
                const date = $('#trackDate').val();

                if (!repairmanId) {
                    alert('请选择维修工');
                    return;
                }

                if (!date) {
                    alert('请选择日期');
                    return;
                }

                $.ajax({
                    url: `/api/admin/tracks/${repairmanId}`,
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    data: {
                        date: date
                    },
                    success: function(response) {
                        displayTrackData(response);
                    }
                });
            }

            // 显示轨迹数据
            function displayTrackData(data) {
                // 清除地图上的覆盖物
                bmap.clearOverlays();

                if (data.tracks.length === 0) {
                    alert('该日期没有轨迹数据');
                    return;
                }

                // 更新统计信息
                $('#totalDistance').text(`${data.totalDistance.toFixed(1)} km`);
                $('#totalDuration').text(`${data.totalDuration.toFixed(1)} 小时`);
                $('#completedOrders').text(`${data.orders.length} 单`);

                // 创建所有轨迹点
                const points = data.tracks.map(track => new BMapGL.Point(track.longitude, track.latitude));
                
                // 创建轨迹线
                const polyline = new BMapGL.Polyline(points, {
                    strokeColor: "#002aff",
                    strokeWeight: 4,
                    strokeOpacity: 0.8,
                    enableClicking: true
                });

                // 创建小车图标
                const trackIcon = new BMapGL.Icon("/images/car.png", new BMapGL.Size(32, 32), {
                    imageSize: new BMapGL.Size(32, 32),
                    anchor: new BMapGL.Size(16, 16)
                });
                const trackMarker = new BMapGL.Marker(points[0], {
                    icon: trackIcon,
                    enableRotation: true
                });
                bmap.addOverlay(trackMarker);

                // 添加起点和终点标记
                const startPoint = points[0];
                const endPoint = points[points.length - 1];
                
                // 创建起点标记
                const startMarker = new BMapGL.Marker(startPoint, {
                    icon: new BMapGL.Icon("/images/start.png", new BMapGL.Size(32, 32), {
                        imageSize: new BMapGL.Size(32, 32),
                        anchor: new BMapGL.Size(16, 32)
                    })
                });
                bmap.addOverlay(startMarker);

                // 创建终点标记
                const endMarker = new BMapGL.Marker(endPoint, {
                    icon: new BMapGL.Icon("/images/end.png", new BMapGL.Size(32, 32), {
                        imageSize: new BMapGL.Size(32, 32),
                        anchor: new BMapGL.Size(16, 32)
                    })
                });
                bmap.addOverlay(endMarker);

                // 添加订单点标记
                data.orders.forEach(order => {
                    const point = new BMapGL.Point(order.longitude, order.latitude);
                    const marker = new BMapGL.Marker(point, {
                        icon: new BMapGL.Icon("/images/order-marker.png", new BMapGL.Size(32, 32), {
                            imageSize: new BMapGL.Size(32, 32),
                            anchor: new BMapGL.Size(16, 32)
                        })
                    });
                    bmap.addOverlay(marker);

                    const infoWindow = new BMapGL.InfoWindow(`
                        <div>
                            <p>订单号：${order.id}</p>
                            <p>时间：${new Date(order.time).toLocaleString()}</p>
                            <p>描述：${order.description}</p>
                        </div>
                    `);
                    marker.addEventListener('click', function() {
                        bmap.openInfoWindow(infoWindow, point);
                    });
                });

                // 创建视野范围对象
                const bounds = new BMapGL.Bounds();
                
                // 将所有轨迹点和订单点加入视野范围
                points.forEach(point => {
                    bounds.extend(point);
                });
                data.orders.forEach(order => {
                    bounds.extend(new BMapGL.Point(order.longitude, order.latitude));
                });

                // 计算视野中心点
                const center = {
                    lng: (bounds.sw.lng + bounds.ne.lng) / 2,
                    lat: (bounds.sw.lat + bounds.ne.lat) / 2
                };

                bmap.centerAndZoom(new BMapGL.Point(center.lng, center.lat), 12);
                // 设置地图视野，确保所有点都在可视范围内

                bmap.setViewport(bounds, {
                    enableAnimation: true,
                    margins: [50, 50, 50, 50]
                });

                // 设置3D视角
                setTimeout(() => {
                    bmap.setTilt(60);
                    bmap.setHeading(45);
                }, 1000);

                // 轨迹动画相关变量
                let currentIndex = 0;
                let playing = false;
                let timer = null;
                const totalPoints = points.length;
                const speed = 500; // 移动速度，单位毫秒

                // 添加播放控制按钮
                const playControl = document.createElement('div');
                playControl.style.cssText = 'position:absolute;left:10px;bottom:10px;padding:10px;background:white;border-radius:5px;z-index:1000;';
                playControl.innerHTML = `
                    <button id="playTrack" class="btn btn-primary btn-sm">
                        <i class="fas fa-play"></i> 播放轨迹
                    </button>
                    <button id="pauseTrack" class="btn btn-secondary btn-sm ms-2" style="display:none">
                        <i class="fas fa-pause"></i> 暂停
                    </button>
                `;
                document.getElementById('trackMap').appendChild(playControl);

                // 播放按钮点击事件
                document.getElementById('playTrack').onclick = function() {
                    if (!playing) {
                        playing = true;
                        this.style.display = 'none';
                        document.getElementById('pauseTrack').style.display = 'inline-block';
                        moveNext();
                    }
                };

                // 暂停按钮点击事件
                document.getElementById('pauseTrack').onclick = function() {
                    playing = false;
                    this.style.display = 'none';
                    document.getElementById('playTrack').style.display = 'inline-block';
                    if (timer) {
                        clearTimeout(timer);
                    }
                };

                // 移动到下一个点
                function moveNext() {
                    if (!playing || currentIndex >= totalPoints - 1) {
                        if (currentIndex >= totalPoints - 1) {
                            currentIndex = 0;
                            trackMarker.setPosition(points[0]);
                            document.getElementById('pauseTrack').style.display = 'none';
                            document.getElementById('playTrack').style.display = 'inline-block';
                            playing = false;
                        }
                        return;
                    }

                    const currentPoint = points[currentIndex];
                    const nextPoint = points[currentIndex + 1];
                    
                    // 计算角度
                    const angle = Math.atan2(
                        nextPoint.lat - currentPoint.lat,
                        nextPoint.lng - currentPoint.lng
                    ) * 180 / Math.PI;
                    
                    // 设置小车位置和角度
                    trackMarker.setPosition(nextPoint);
                    trackMarker.setRotation(angle);

                    // 绘制已经走过的路线
                    const passedPoints = points.slice(0, currentIndex + 2);
                    const passedLine = new BMapGL.Polyline(passedPoints, {
                        strokeColor: "#0015ff",
                        strokeWeight: 4,
                        strokeOpacity: 0.8
                    });
                    bmap.clearOverlays();
                    bmap.addOverlay(passedLine);
                    bmap.addOverlay(trackMarker);
                    bmap.addOverlay(startMarker);
                    bmap.addOverlay(endMarker);

                    // 添加订单点标记
                    data.orders.forEach(order => {
                        const orderPoint = new BMapGL.Point(order.longitude, order.latitude);
                        const marker = new BMapGL.Marker(orderPoint, {
                            icon: new BMapGL.Icon("/images/order-marker.png", new BMapGL.Size(32, 32), {
                                imageSize: new BMapGL.Size(32, 32),
                                anchor: new BMapGL.Size(16, 32)
                            })
                        });
                        bmap.addOverlay(marker);
                    });

                    currentIndex++;
                    timer = setTimeout(moveNext, speed);
                }

                // 更新时间轴
                updateTimeline(data);
            }

            // 更新时间轴
            function updateTimeline(data) {
                const timeline = $('#trackTimeline');
                timeline.empty();

                // 合并轨迹点和订单点，按时间排序
                const events = [
                    ...data.tracks.map(track => ({
                        time: track.createTime,
                        type: 'location',
                        latitude: track.latitude,
                        longitude: track.longitude,
                        address: track.address
                    })),
                    ...data.orders.map(order => ({
                        time: order.time,
                        type: 'order',
                        description: order.description
                    }))
                ].sort((a, b) => new Date(a.time) - new Date(b.time));

                events.forEach(event => {
                    const time = new Date(event.time).toLocaleTimeString();
                    const content = event.type === 'location' 
                        ? `位置更新：经：${event.latitude} 纬：${event.longitude}`
                        : `订单完成：${event.description}`;
                    const icon = event.type === 'location' 
                        ? 'fa-map-marker-alt text-primary'
                        : 'fa-check-circle text-success';

                    timeline.append(`
                        <div class="d-flex mb-3">
                            <div class="me-3">
                                <i class="fas ${icon}"></i>
                            </div>
                            <div>
                                <div class="text-muted small">${time}</div>
                                <div>${content}</div>
                            </div>
                        </div>
                    `);
                });
            }

            // 添加论坛管理相关函数
            function loadForumPosts(page = 1) {
                $.ajax({
                    url: '/api/forum/posts',
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    data: {
                        page: page,
                        size: 10
                    },
                    success: function(response) {
                        const tbody = $('#forum-posts-table');
                        tbody.empty();
                        
                        response.posts.forEach(post => {
                            tbody.append(`
                                <tr>
                                    <td>${post.id}</td>
                                    <td>${post.title}</td>
                                    <td>${post.realName || post.username}</td>
                                    <td>${post.userType === 1 ? '用户' : '维修工'}</td>
                                    <td>${new Date(post.createTime).toLocaleString()}</td>
                                    <td>${getPostStatus(post.status)}</td>
                                    <td>
                                        <button class="btn btn-sm btn-info" onclick="viewPost(${post.id})">查看</button>
                                        <button class="btn btn-sm btn-danger" onclick="deletePost(${post.id})">删除</button>
                                    </td>
                                </tr>
                            `);
                        });
                        
                        // 更新分页控件
                        updatePagination(response.total, page);
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            }

            function getPostStatus(status) {
                const statusMap = {
                    0: '待审核',
                    1: '已发布',
                    2: '已删除'
                };
                return statusMap[status] || '未知状态';
            }

            function updatePagination(total, currentPage) {
                const totalPages = Math.ceil(total / 10);
                const pagination = $('#forum-pagination');
                pagination.empty();
                
                // 上一页
                pagination.append(`
                    <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                        <a class="page-link" href="#" onclick="loadForumPosts(${currentPage - 1})">上一页</a>
                    </li>
                `);
                
                // 页码
                for (let i = 1; i <= totalPages; i++) {
                    pagination.append(`
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="loadForumPosts(${i})">${i}</a>
                        </li>
                    `);
                }
                
                // 下一页
                pagination.append(`
                    <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                        <a class="page-link" href="#" onclick="loadForumPosts(${currentPage + 1})">下一页</a>
                    </li>
                `);
            }

            function viewPost(postId) {
                $.ajax({
                    url: `/api/forum/posts/${postId}`,
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function(post) {
                        // 显示帖子详情模态框
                        $('#postTitle').text(post.title);
                        $('#postContent').html(post.content);
                        $('#postAuthor').text(post.realName || post.username);
                        $('#postTime').text(new Date(post.createTime).toLocaleString());
                        $('#postModal').modal('show');
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            logout();
                        }
                    }
                });
            }

            function deletePost(postId) {
                if (confirm('确定要删除这个帖子吗？')) {
                    $.ajax({
                        url: `/api/forum/posts/${postId}`,
                        type: 'DELETE',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        },
                        success: function() {
                            loadForumPosts();
                            alert('帖子删除成功');
                        },
                        error: function(xhr) {
                            if (xhr.status === 401) {
                                logout();
                            }
                        }
                    });
                }
            }
        });
    </script>
</body>
</html> 